<template>
  <div class="p-4">
    <div class="job-wrap">
      <div class="job-calendar" >
        <a-calendar v-model:value="dateValue" @panelChange="onPanelChange">
          <template #headerRender="{ value: current, onChange }">
              <div class="calendar-top">
                <div class="title-wrap">
                  <div class="title">任务管理</div>
                  <a-select
                    :dropdown-match-select-width="false"
                    class="my-year-select"
                    :value="String(current.year())"
                    @change="
                      newYear => {
                        onChange(current.year(+newYear));
                      }
                    "
                  >
                    <a-select-option
                      v-for="val in getYears(current)"
                      :key="String(val)"
                      class="year-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    class="my-year-select"
                    style="margin-left: 15px;"
                    :dropdown-match-select-width="false"
                    :value="String(current.month())"
                    @change="
                      selectedMonth => {
                        onChange(current.month(parseInt(String(selectedMonth), 10)));
                      }
                    "
                >
                    <a-select-option
                      v-for="(val, index) in getMonths(current)"
                      :key="String(index)"
                      class="month-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                </div>
                <div class="icon">
                    <div class="icon-calendar"><Icon icon="lucide:calendar"></Icon></div>
                    <div class="icon-list" @click="() => router.push({ path: '/uav/job' })"><Icon icon="gg:list"></Icon></div>
                </div>
                <div class="search-mod">
                  <a-button class="addTask" preIcon="ant-design:plus-outlined" @click="() => openTaskModal(PageType.Add)"> 创建任务 </a-button>
                  <a-select 
                    style="width: 143px;"
                    v-model:value="queryParam.status" allowClear
                    :options="optionsList.status"
                    @change="value => selectChange('status', value)"
                  />
                  <a-select 
                    style="width: 143px;" v-model:value="queryParam.jobType"
                    allowClear :options="optionsList.jobType"
                    @change="value => selectChange('jobType', value)"
                  />
                  <a-input-search
                    allowClear
                    v-model:value="queryParam.jobName"
                    placeholder="请搜索任务名称"
                    style="width: 200px;"
                    @search="enterSearch"
                  />
                </div>
              </div>
          </template>
          <template #dateCellRender="{ current }">
            <ul class="events"
            >
              <li v-for="item in getListData(current)"
                :key="item.content" class="job-calendar-item"
                :class="activeItem.id && item?.id && activeItem.id === item?.id && 'active'"
              >
                <a-popover
                  v-model:open="popoverVisible"
                  trigger="click"
                  :destroyTooltipOnHide="true"
                  :getPopupContainer="getPopupContainer"
                >
                  <template #content>
                    <div class="popover-content">
                      <div class="title-wrap">
                        <div class="icon-wrap">
                          <img class="icon" :src="getTaskTypeIcon" />
                          <div class="desc">条件任务</div>
                        </div>
                        <div class="title">{{ activeItem.taskName }}</div>
                      </div>
                      <div class="middle">
                        <div class="item status">
                          <div class="icon-wrap">
                            <img class="title-icon" :src="jobImgUrl('执行状态-气泡')" />
                          </div>
                          <div class="item-content">
                            <div class="label">执行状态</div>
                            <div class="value"> {{ TaskStatusOps.find(item => item.value === activeItem.status)?.label || '' }}</div>
                          </div>
                        </div>
                        <div class="item wayLine">
                          <div class="icon-wrap">
                            <img class="title-icon" :src="jobImgUrl('关联航线-气泡')" />
                          </div>
                          <div class="item-content">
                            <div class="label">关联航线</div>
                            <div class="value" @click="() => popoverHandleClick('viewWayLine')">
                              <div class="icon"><Icon class="icon" :size="14" icon="bx:map"></Icon></div> 
                              <div class="txt">{{ activeItem.waylineName }}</div>
                            </div>
                          </div>
                        </div>
                        <div class="item device">
                          <div class="icon-wrap">
                            <img class="title-icon" :src="jobImgUrl('关联设备-气泡')" />
                          </div>
                          <div class="item-content">
                            <div class="label">关联设备</div>
                            <div class="value"> {{ activeItem.deviceName }}</div>
                          </div>
                        </div>
                        <div class="item medium">
                          <div class="icon-wrap">
                            <img class="title-icon" :src="jobImgUrl('媒体上传-气泡')" />
                          </div>
                          <div class="item-content">
                            <div class="label">媒体上传</div>
                            <div class="value"> {{ activeItem.result }}</div>
                          </div>
                        </div>
                      </div>
                      <div class="footer">
                        <div class="left">
                           创建人：{{activeItem.createBy }}
                        </div>
                        <div class="right" id="modal-right">
                          <Icon class="icon" :class="!btnAuthTemplate('查看轨迹') && 'disabled'" :size="18" icon="carbon:map" @click="() => popoverHandleClick('viewWayLine')"></Icon>
                          <Icon class="icon" :class="!btnAuthTemplate('复制') && 'disabled'" :size="18" icon="radix-icons:copy" @click="() => popoverHandleClick('copy')"></Icon>
                          <Icon class="icon" :class="!btnAuthTemplate('删除') && 'disabled'" :size="18" icon="uiw:delete" @click="() => popoverHandleClick('del')"></Icon>
                        </div>
                      </div>
                    </div>
                  </template>
                  <a-badge  class="badge" :status="item.type" :text="item.content"  @click="clickDetail(item, current)"/>
                </a-popover>
              </li>
            </ul>
          </template>
        </a-calendar>
      </div>
      <AddJob  
        :pageType="pageType"
        :jobData="jobData"
        @success="success" 
        @register="registerAddJob" 
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { inject, onMounted, reactive, ref, computed, nextTick, ComponentPublicInstance  } from 'vue';
import AddJob from '../addJob.vue'
import { useMessage } from '/@/hooks/web/useMessage';
import ApiListOptions from '/@/api/type'
import { useRouter } from "vue-router";
import Icon from '/@/components/Icon/index';
import { PageType, TaskStatus, TaskStatusOps, TaskType, TaskTypeOps } from '/@/constants/job'
import { useModal } from '/@/components/Modal';
import dayjs, { Dayjs } from 'dayjs';
import { getIconUrl } from '/@/utils'

const imgTaskTypeList = [{
    value: TaskType.InstantTask,
    label: '即时任务',
  },{
    value: TaskType.ScheduledTask,
    label: '定时任务',
  },{
    value: TaskType.RepeatingTask,
    label: '重复任务',
  },{
    value: TaskType.ConditionalTask,
    label: '条件任务',
  }
]
type refItem = Element | ComponentPublicInstance | null;
const getPopupContainer = triggerNode => triggerNode.parentNode;
//const getPopupContainer = () => document.querySelector('.job-calendar') as HTMLElement
const router = useRouter();
const dateValue = ref<Dayjs>();
const $http: ApiListOptions | undefined = inject('api')
const { createMessage , createConfirm } = useMessage();
const pageType = ref<string>('')
const jobData = ref<any>()
const [registerAddJob, { openModal: modalAddJob }] = useModal()
let queryParam = reactive<any>({
  year: '',
  month: '',
  jobType: '',
  status: '',
  jobName: ''
})
const curDay = ref()  // 激活的天数
const optionsList = ref({
  status: TaskStatusOps,
  jobType: TaskTypeOps,
})   // 字典数据
const dataList = ref<any>()  // 当前月份数据
const activeItem = ref<any>({})  // 点击选中的数据
const popoverVisible = ref<boolean>(false);
// const eventsRef = ref()
// /** 动态设置Ref */
// const handleSetRef = (el: refItem, value: any) => {
//   const date = value.date()
//   const month = value.month() + 1
//   console.log("curDay.value", curDay.value, date)
//   if (el && queryParam.month === month && curDay.value === date) {
//     eventsRef.value = el;
//   }
// }
const jobImgUrl = (name: string, suffix = 'png') => {
  return getIconUrl(name, 'icons/job/', suffix)
}

//权限控制  true: 有权限  false: 无权限 (用在template上)
const btnAuthTemplate = computed(() => (type: string): boolean => {
  const { status } = activeItem.value
  const btnAccess = {
    '复制': true,
    '删除': ![TaskStatus.Progress].includes(status),
    '查看轨迹': [TaskStatus.Success].includes(status),
  }
  return btnAccess[type] || false
})

const getTaskTypeIcon = computed((): string => {
      const imgName = imgTaskTypeList.find(item => item.value === activeItem.value.jobType)?.label || ''
      //console.log("imgName", imgName)
      return imgName ? jobImgUrl(imgName) : ''
  }
)


const onPanelChange = (value: Dayjs, mode: string) => {
  //console.log("onPanelChange==value", value.year(), value.month() + 1, value.date())
  queryParam.year = value.year()
  queryParam.month = value.month() + 1
  queryParam.day = value.date()
  getData()
};

async function getData() {
  const params = { ...queryParam }
  Object.keys(params).forEach( key => {
    if(params[key] === '' || params[key] === null){
      params[key] = undefined
    }
  })
  const result = await $http?.getTaskQureyTaskListByMonth({
    ...params
  })
  //console.log("result", result)
  if(result){
    dataList.value = result 
  }
}

onMounted(async () => {
  // 初始化字典
  queryParam.year = dayjs().year()
  queryParam.month = dayjs().month() + 1
  curDay.value = dayjs().date()
  getData()
});

const getListData = (value: Dayjs) => {
  let renderList;
  const date = value.date()
  const month = value.month() + 1
  //console.log("getListData--valueTemp", month, date)
  if(date >= 0 && dataList.value?.length && queryParam.month === month){
    const dataListTemp =  dataList.value
    const { wayLineTaskVoList } = dataListTemp[date - 1] || {}
    //console.log("getListData--wayLineTaskVoList", wayLineTaskVoList)
    renderList = wayLineTaskVoList?.length ? wayLineTaskVoList.map((item: any) => {
        return {
          type: item?.status === TaskStatus.Success ? 'success' : 'warning',
          content: `${ item?.planTime || ''}  ${ item?.taskName || ''}`,
          id: item.id,  // 唯一标识
          initialData: { ...item }
        }
    }) : []
  }
  return renderList || [];
};

const getMonths = (value: Dayjs) => {
  const localeData = value.localeData()
  const months = []
  for (let i = 0; i < 12; i++) {
    months.push(localeData.monthsShort(value.month(i)))
  }
  return months
};

const getYears = (value: Dayjs) => {
  const year = value.year();
  const years: any[] = [];
  for (let i = year - 10; i < year + 10; i += 1) {
    years.push(i);
  }
  return years;
};

const openTaskModal = async (type) => {
  popoverVisible.value = false
  await nextTick();
  pageType.value = type;
  modalAddJob(true);
}

const clickDetail = (item, value) => {
  //console.log("当天的当前任务数据--item", item.initialData)
  curDay.value = value.date()    // 缓存激活的天数 
  activeItem.value = item.initialData
  popoverVisible.value = true
}

const selectChange = (type: string, value?: any) => {
  //console.log("value", value)
  switch(type){
    case "status":
      {
        queryParam.status = value ?? ''
        getData()
      }
      break
    case "jobType":
      {
        queryParam.jobType = value ?? ''
        getData()
      }
      break
  }
}

const enterSearch = (value) => {
  //console.log("查询文件==value", value)
  queryParam.jobName = value
  getData()
}

const popoverHandleClick = async (type: string) => {
  switch(type){
    case 'viewWayLine':  // TODO: 需要杨柳那边做好轨迹详情!
      {
        if(!(btnAuthTemplate.value('查看轨迹'))) return
        popoverVisible.value = false
        await nextTick()
      }
    break;
    case 'copy':
      {
        if(!(btnAuthTemplate.value('复制'))) return
        const result = await $http?.getWaylinejobGet({ jobId: activeItem.value.jobId })
        if(result){
          //console.log("开始复制---打开弹框")
          popoverVisible.value = false
          //await nextTick()
          pageType.value = PageType.COPY
          jobData.value = result
          modalAddJob(true)
        }
      }
    break;
    case 'del':
      {
        if(!(btnAuthTemplate.value('删除'))) return
        //console.log("删除任务--activeItem", activeItem.value)
        createConfirm({
          title: '删除任务',
          content: '确定删除当前任务吗？',
          iconType: 'warning',
          getContainer: (): any =>  { return document.getElementById('modal-right') },
          //getContainer: triggerNode => triggerNode.parentNode,
          onOk: async () => {
            await $http?.deleteWaylinejobDel(activeItem.value.jobId)
            popoverVisible.value = false
            await nextTick()
            getData()
          },
          onCancel: () => {},
        });
      }
    break;
  }  
}

function success() {
  getData()
}

</script>
<style lang="less" scoped>
.job-wrap{
  .job-calendar{
    width: 100%;
    .calendar-top{
      position: relative;
      padding: 10px;
      padding-left: 0px;
      display: flex;
      justify-content: space-between;
      .title-wrap{
        display: flex;
        height: 30px;
        align-items: center;
        .title{
          width: 100px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          color: #333333;
          text-align: center;
        }
      }
      .icon{
          margin-left: 100px;
          width: 120px;
          height: 100%;
          display: flex;
          align-items: center;
          .icon-calendar{
            width: 38px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            background: linear-gradient(56deg, #2C9AD6 0%, #167DB5 100%);
            border-radius: 16px 0px 0px 16px;
          }
          .icon-list{
            width: 38px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      .search-mod{
        .addTask {
          background: linear-gradient(315deg, #2997d2 0%, #1880b9 100%);
          box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.16);
          border-radius: 2px;
          color: white;
        }
      }
    }
    .events{
      .job-calendar-item{
        &.active{
          z-index: 999;
          background: linear-gradient(180deg, #E7F4F9 0%, rgba(197,224,237,0) 100%);
          border-radius: 16px;
          border: 1px solid rgba(11,121,181,0.6);
        }
        /deep/ .ant-popover-content{
          .popover-content{
              width: 486px;
              height: 300px;
              background: #FFFFFF;
              border-radius: 2px;
              z-index: 9999;
              .title-wrap{
                width: 100%;
                height: 70px;
                padding: 0px 28px;
                display: flex;
                align-items: center;
                background:  rgba(147,197,253,0.5);
                .icon-wrap{
                  display: flex;
                  flex-direction: column;
                  .icon{
                    width: 41px;
                    height: 36px;
                  }
                  .desc{
                    color: #333;
                  }
                }
                .title{
                  height: 22px;
                  margin-left: 30px;
                  font-size: 16px;
                  font-family: PingFangSC, PingFang SC;
                  font-weight: 500;
                  color: #333333;
                  line-height: 22px;
                }
              }
              .middle{
                width: 100%;
                height: 200px;
                padding: 0px 28px;
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                .item{
                  width: 50%;
                  display: flex;
                  .icon-wrap{
                    .title-icon{
                      width: 45px;
                      height: 45px;
                    }
                  }
                  .item-content{
                    width: 80%;
                    margin-left: 20px;
                    display: flex;
                    flex-direction: column;
                    .label{
                      font-size: 14px;
                      font-family: PingFangSC, PingFang SC;
                      font-weight: 600;
                      color: #333;
                    }
                    .value{
                      font-size: 14px;
                      font-family: PingFangSC, PingFang SC;
                      font-weight: 400;
                      color: #666;
                      overflow: hidden;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                    }
                  }
                  &.status{

                  }
                  &.wayLine{
                    .value{
                      display: flex;
                      .icon{
                        margin-right: 1px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        color: #167DB5;
                      }
                      .txt{
                        font-size: 14px;
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        color: #167DB5;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        :hover{
                          border-bottom: 1px solid #167DB5;
                        }
                      }
                    } 
                  }
                  &.device{

                  }
                  &.medium{

                  }
                }
              }
              .footer{
                width: 100%;
                height: 30px;
                padding: 0px 28px;
                display: flex;
                justify-content: space-between;
                .left{
                  font-size: 14px;
                  font-family: PingFangSC, PingFang SC;
                  font-weight: 400;
                  color: #666666;
                }
                .right{
                  display: flex;
                  font-size: 18px;
                  .icon{
                    width: 24px;
                    height: 24px;
                    margin-left: 10px;
                    
                    &.disabled{
                      cursor: not-allowed;
                    }
                  }
                }
              }
          }
        }
        .badge{
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
<style lang="less">
.job-wrap{
  .ant-picker-body{
    background: rgba(237,248,255,0.5);
    border-radius: 4px;
    .ant-picker-cell-selected{
      z-index: 9999;
    }
  }
}
</style>

